package com.kim.bookshop.cart.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;

import com.kim.bookshop.book.bean.Book;
import com.kim.bookshop.book.service.BookService;
import com.kim.bookshop.cart.bean.Cart;
import com.kim.bookshop.cart.bean.CartItem;
import com.opensymphony.xwork2.ActionSupport;

public class CartAction extends ActionSupport{
	
	private static final long serialVersionUID = 7139269645658187078L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	private ServletContext application;
	private BookService bookService;
	private ApplicationContext ctx;
	
	public CartAction(){
		request=ServletActionContext.getRequest();
		response=ServletActionContext.getResponse();
		session=request.getSession();
		application= session.getServletContext();
		ctx=(ApplicationContext) application.getAttribute("ApplicationContext"); 
		bookService=(BookService) ctx.getBean("bookService");
	}
	
	/*
	 * 加入购物车
	 */
	public String add() throws Exception {
		
		Cart cart=(Cart) session.getAttribute("cart");//得到购物车
		if(cart!=null){
		
		
		String bid=request.getParameter("bid");
		Book book=bookService.load(bid);
		int count=Integer.parseInt(request.getParameter("count"));
		CartItem cartItem=new CartItem();
		cartItem.setBook(book);
		cartItem.setCount(count);
		cart.add(cartItem);
		return SUCCESS;
		}else{
			response.sendRedirect("/BookShop/UserLogin.jsp");
			return null;
		}
	}

	/**
	 * 清空购物车
	 * @return
	 */
	public String clear(){
		Cart cart = (Cart)request.getSession().getAttribute("cart");
		cart.clear();
		return SUCCESS;
	}

	/**
	 * 移除
	 * @return
	 */
	public String delete(){
		Cart cart = (Cart)request.getSession().getAttribute("cart");
		String bid=request.getParameter("bid");
		cart.delete(bid);
		return SUCCESS;
	}
	
}
